// import "@/utils/sso";
import Cookies from "js-cookie";
import { getConfig } from "@/config";
import NProgress from "@/utils/progress";
import { buildHierarchyTree } from "@/utils/tree";
import remainingRouter from "./modules/remaining";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { isUrl, openLink, storageLocal, isAllEmpty, cloneDeep, isFunction } from "@pureadmin/utils";
import {
  ascending,
  getTopMenu,
  initRouter,
  isOneOfArray,
  getHistoryMode,
  findRouteByPath,
  handleAliveRoute,
  formatTwoStageRoutes,
  formatFlatteningRoutes,
  addPathMatch,
  handleAsyncRoutes
} from "./utils";
import {
  type Router,
  createRouter,
  type RouteRecordRaw,
  type RouteComponent
} from "vue-router";
import {
  type DataInfo,
  userKey,
  removeToken,
  multipleTabsKey,
  getToken
} from "@/utils/auth";
import { PLATFORM_LIST, PLATFORM_Map } from "@/constant/index";
import { usePageVariablesStoreHook } from '@/store/modules/pageVariables'
import { getApplicationSystemList } from '@/api/operate/application-system/index'
import applicationSystem from "@/assets/images/leftminsvg/application-system.svg";
import { message } from "@/utils/message";
import { getSelfInfo, getUserRole } from "@/api/user";
import { setUserKey } from "@/utils/auth";
import { getUserProjectRole } from "@/api/operate/work-management/work-management";
import { routerArrays } from "@/store/utils";
import { closeAllDialog } from "@/components/ReDialog";
import { closePopover } from "@/components/customPopover";
/** 自动导入全部静态路由，无需再手动引入！匹配 src/router/modules 目录（任何嵌套级别）中具有 .ts 扩展名的所有文件，除了 remaining.ts 文件
 * 如何匹配所有文件请看：https://github.com/mrmlnc/fast-glob#basic-syntax
 * 如何排除文件请看：https://cn.vitejs.dev/guide/features.html#negative-patterns
 */
const modules: Record<string, any> = import.meta.glob(
  ["./modules/**/*.ts", "!./modules/**/remaining.ts"],
  {
    eager: true
  }
);

/** 原始静态路由（未做任何处理） */
const routes = [];

Object.keys(modules).forEach(key => {
  routes.push(modules[key].default);
});

/** 导出处理后的静态路由（三级及以上的路由全部拍成二级） */
// export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes(
//   formatFlatteningRoutes(buildHierarchyTree(ascending(routes.flat(Infinity))))
// );

/** 获取平台对应路由 */
const getPlatformRouter = (routes: any[], platform = PLATFORM_Map.manage): any[] => {
  if (isAllEmpty(platform)) {
    platform = PLATFORM_Map.manage
  }
  let copyRoutes = cloneDeep(routes);
  // 过滤路由
  // return routes.filter((item: any) => {
  return copyRoutes.filter((item: any) => {
    // if (item.path == '/welcome') {
    //   console.log(routes);
    // }

    // 如果meta中包含platform
    if (item.meta?.platform) {
      // 如果platform包含当前平台返回
      if (item.meta?.platform.includes(platform)) {
        // 如果存在子路由，递归
        if (item.children) {
          item.children = getPlatformRouter(item.children, platform);
        }
        return true;
      } else {
        return false;
      }
    } else {
      // 如果meta中不包含platform则直接返回
      if (item.children) {
        item.children = getPlatformRouter(item.children, platform);
      }
      return true;
    }
  })
}
export const constantRoutes: Array<RouteRecordRaw> = ascending(
  getPlatformRouter(routes, usePageVariablesStoreHook().getPlatform() ?? storageLocal().getItem("platform")).flat(Infinity)
).concat(...remainingRouter)

/** 用于渲染菜单，保持原始层级 */
export const constantMenus: Array<RouteComponent> = ascending(
  routes.flat(Infinity)
).concat(...remainingRouter);

/** 不参与菜单的路由 */
export const remainingPaths = Object.keys(remainingRouter).map(v => {
  return remainingRouter[v].path;
});

/** 创建路由实例 */
export const router: Router = createRouter({
  history: getHistoryMode(import.meta.env.VITE_ROUTER_HISTORY),
  routes: constantRoutes.concat(...(remainingRouter as any)),
  strict: true,
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      if (savedPosition) {
        return savedPosition;
      } else {
        if (from.meta.saveSrollTop) {
          const top: number =
            document.documentElement.scrollTop || document.body.scrollTop;
          resolve({ left: 0, top });
        }
      }
    });
  }
});
export const resetHomePage = () => {
  useMultiTagsStoreHook().handleTags("equal", [
    {
      path: "/welcome",
      meta: {
        title: `${PLATFORM_LIST[localStorage.getItem('platform')]?.title ?? ''}首页`,
        icon: "ep:home-filled"
      }
    }
  ]);
}
/** 重置路由 */
// 导出一个函数resetRouter，用于重置路由
export function resetRouter(to?, jump = true) {

  // 获取路由记录
  router.getRoutes().forEach(route => {
    const { name, meta } = route;
    if (name && router.hasRoute(name)) {
      router.removeRoute(name);
    }
  });
  let platformRouters = formatTwoStageRoutes(
    formatFlatteningRoutes(
      buildHierarchyTree(ascending(getPlatformRouter(routes, usePageVariablesStoreHook().getPlatform() ?? storageLocal().getItem("platform")).flat(Infinity)))
    )
  );
  router.options.routes = platformRouters
  router.addRoute(platformRouters[0])
  addRoutes(remainingRouter)
  usePermissionStoreHook().clearAllCachePage();
  usePermissionStoreHook().setConstantMenus(ascending(
    getPlatformRouter(routes, usePageVariablesStoreHook().getPlatform() ?? storageLocal().getItem("platform")).flat(Infinity)
  ).concat(...remainingRouter));
  if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.operate && getToken()) {
    getApplicationSystemList().then(res => {
      let pathList = []
      if (res.result && res.result.length > 0) {
        pathList = [
          {
            path: "/application-system",
            redirect: `/application-system/application-system/${res.result[0].systematicId}`,
            component: () => import("@/layout/index.vue"),
            meta: {
              title: "应用系统",
              showLink: true,
              icon: applicationSystem,
              rank: 9,
            },
            children: []
          }
        ]
        pathList[0].children.push(...res.result.map(item => {
          return {
            path: `/application-system/application-system/${item.systematicId}`,
            name: `/application-system/application-system/${item.systematicId}`,
            component: () => import("@/views/operate/application-system/index.vue"),
            meta: {
              title: item.systematicName,
              showLink: true,
              showParent: true
            }
          }
        }))
      }
      addRoutes(pathList)
      usePermissionStoreHook().handleWholeMenus(pathList)
      if (jump) {
        if (to && router.hasRoute(to.name)) {
          router.push(to.fullPath);
        } else {
          router.push("/")
        }
      }
    }).catch(err => {
      message('应用系统加载失败!', { type: 'error' })
      usePermissionStoreHook().handleWholeMenus([])
      if (jump) {
        if (to && router.hasRoute(to.name)) {
          router.push(to.fullPath);
        } else {
          router.push("/")
        }
      }
    })
  } else {
    usePermissionStoreHook().handleWholeMenus([])
    addPathMatch();
    if (jump) {
      if (to && router.hasRoute(to.name)) {
        router.push(to.fullPath);
      } else {
        router.push("/")
      }
    }
  }
}
// 添加路由
const addRoutes = (routes: any[]) => {
  routes.forEach((route: any) => {
    router.addRoute(route)
  })
}

/** 路由白名单 */
const whiteList = ["/login", "/protocolContent"];

const { VITE_HIDE_HOME } = import.meta.env;

router.beforeEach((to: ToRouteType, _from, next) => {
  closePopover()
  closeAllDialog()
  if (to.meta?.keepAlive) {
    handleAliveRoute(to, "add");
    // 页面整体刷新和点击标签页刷新
    if (_from.name === undefined || _from.name === "Redirect") {
      handleAliveRoute(to);
    }
  }
  const userInfo = storageLocal().getItem<DataInfo<number>>(userKey);
  // NProgress.start();
  const externalLink = isUrl(to?.name as string);
  if (!externalLink) {
    to.matched.some(item => {
      if (!item.meta.title) return "";
      const Title = getConfig().Title;
      if (Title) document.title = `${item.meta.title} | ${Title}`;
      else document.title = item.meta.title as string;
    });
  }
  /** 如果已经登录并存在登录信息后不能跳转到路由白名单，而是继续保持在当前页面 */
  function toCorrectRoute() {
    whiteList.includes(to.fullPath) ? next(_from.fullPath) : next();
  }
  if (Cookies.get(multipleTabsKey) && userInfo) {
    // 无权限跳转403页面
    let userAuths = [''];
    if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.manage) {
      userAuths = userInfo?.userInfo?.roles?.manage
    } else if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.operate) {
      userAuths = userInfo?.userInfo?.roles?.operate
    }
    if (to.meta?.roles && !isOneOfArray(to.meta?.roles, userAuths) && userAuths.length != 0) {
      next({ path: "/error/403" });
    }
    // 开启隐藏首页后在浏览器地址栏手动输入首页welcome路由则跳转到404页面
    if (VITE_HIDE_HOME === "true" && to.fullPath === "/welcome") {
      next({ path: "/error/404" });
    }
    if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.operate) {
      if (usePageVariablesStoreHook().operateProjectInfo?.expireStatus == 2
        && !['/welcome', '/login', '/error/expire', '/error/noProjectSelected', '/protocolContent'].includes(to.path)) {
        next({ path: "/error/expire" });
      } else if ((storageLocal().getItem(userKey).userInfo?.isSuper == 2 && (usePageVariablesStoreHook().getOperate().checkedProject == null || usePageVariablesStoreHook().getOperate().checkedProject == 0))
        && !['/login', '/error/expire', '/error/noProjectSelected', '/protocolContent'].includes(to.path)) {
        next({ path: "/error/noProjectSelected" });
      }
    }
    if (_from?.name) {
      // name为超链接
      if (externalLink) {
        openLink(to?.name as string);
        // NProgress.done();
      } else {
        toCorrectRoute();
      }
    } else {
      // 刷新
      if (
        usePermissionStoreHook().wholeMenus.length === 0 &&
        to.path !== "/login"
      ) {
        getSelfInfo().then(res => {
          if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.manage) {
            getUserRole().then(res1 => {
              let userInfo = storageLocal().getItem(userKey).userInfo
              Object.assign(userInfo, res.result.userInfo)
              if (userInfo.roles) {
                userInfo.roles.manage = res1.result.data
              } else {
                userInfo.roles = {
                  manage: res1.result.data
                }
              }
              setUserKey(userInfo.nickname, res1.result.data, userInfo);
              if (['/error/expire', '/error/noProjectSelected'].includes(to.path)) {
                resetRouter()
              } else {
                resetRouter(to)
              }
            }).catch(() => {
              message('获取权限失败', { type: 'error' })
            })
          } else if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.operate) {
            getUserProjectRole().then(res1 => {
              let userInfo = storageLocal().getItem(userKey).userInfo
              Object.assign(userInfo, res.result.userInfo)
              if (userInfo.roles) {
                userInfo.roles.operate = res1.result.data
              } else {
                userInfo.roles = {
                  operate: res1.result.data
                }
              }
              setUserKey(userInfo.nickname, res1.result.data, userInfo);
              resetRouter(to)
            }).catch(() => {
              message('获取权限失败', { type: 'error' })
            })
          } else {
            resetRouter(to)
          }
        }).catch(() => {
          message('获取个人信息失败', { type: 'error' })
        })
        if (!useMultiTagsStoreHook().getMultiTagsCache) {
          const { path } = to;
          const route = findRouteByPath(path, router.options.routes[0].children);
          // query、params模式路由传参数的标签页不在此处处理
          if (route && route.meta?.title) {
            useMultiTagsStoreHook().handleTags("push", {
              path: route.path,
              name: route.name,
              meta: route.meta,
            });
          }
        }
      } else {
        toCorrectRoute();
      }
    }
  } else {
    if (to.path !== "/login") {
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        removeToken();
        next({ path: "/login" });
      }
    } else {
      next();
    }
  }
});

router.afterEach(() => {
  // NProgress.done();
});

export default router;
